package cn.ddm.hrm.service.impl;

import cn.ddm.hrm.client.ThirdPartyClient;
import cn.ddm.hrm.domain.VipBase;
import cn.ddm.hrm.exception.ErrorCode;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.mapper.VipBaseMapper;
import cn.ddm.hrm.service.IVerifyCodeService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.Constants;
import cn.ddm.hrm.util.StrUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Autowired
    private ThirdPartyClient thirdPartyClient;

    @Override
    public AjaxResult sendRegisterSmsCode(Map<String, String> params) {
        // 获取参数
        String mobile = params.get("mobile");
        String imageCode = params.get("imageCode");
        String imageCodeKey = params.get("imageCodeKey");

        // 参数校验
        ValidUtils.assertNotNull(mobile, ErrorCode.CODE_400_USER_PHONE);
        ValidUtils.assertNotNull(imageCode, ErrorCode.CODE_400_USER_CODE);
        ValidUtils.assertNotNull(imageCodeKey, ErrorCode.CODE_400_USER_IMG_CODE);

        // 判断图片验证码是否过期,是否正确
        thirdPartyClient.verifyImgCode(params);

        // 查询用户是否已经注册
        List<VipBase> user = vipBaseMapper.selectList(new EntityWrapper<VipBase>().eq("phone", mobile));
        ValidUtils.assertListNull(user, ErrorCode.CODE_400_USER_PHONE_ISNULL);

        // 生成验证码
        HashMap<String, String> phoneMap = new HashMap<>();
        phoneMap.put("key", Constants.REGISTER_CODE_PREFIX + mobile);
        phoneMap.put("phone",mobile);
        phoneMap.put("expire", "3");
        phoneMap.put("codeCount", "4");

        return thirdPartyClient.sendSmsVerifyCode(phoneMap);
    }
}
